#!/usr/bin/python
# -*- coding: latin1 -*-
"""

    Name: writer.py

    Author: Enrico Bortolazzi - Veia Progetti s.r.l.

    Comment: brailleMusicML writer

    Version: 1.0

    Date: Fri Aug 24, 2007

------------------------------------------------------------------------

Copyright (c) 2007, Veia Progetti s.r.l. - http://www.veia.it

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the distribution.

    Neither name of Veia Progetti s.r.l. nor the name of its contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
import codecs
import xml.sax.saxutils as sxu
import _brailleMusicML

def _writeElement(element, processing=None, entities=_brailleMusicML.get_braille_entities()):
    #if not element: return ''
    if element is None: return ''

    attrs = []
    if hasattr(element, '_req_attrs'):
        for a in element._req_attrs:
            #v = getattr(element, '%s' % a)
            #attrs.append('%s=%s' % (_brailleMusicML.name_unmangle(a), sxu.quoteattr(unicode(v))))
            v = getattr(element, a)
            if v is not None:
                attrs.append('%s=%s' % (_brailleMusicML.name_unmangle(a), sxu.quoteattr(unicode(str(v)))))
    if hasattr(element, '_attrs'):
        for a in element._attrs:
            #v = getattr(element, '%s' % a, None)
            v = getattr(element, a, None)
            if v:  #default value checked by type (see _NamedEnumerator.__nonzero__)
                #v = unicode(str(v))  #__repr__ defined for each attribute
                if not isinstance(v, unicode):
                    v = unicode(str(v))
                attrs.append('%s=%s' % (_brailleMusicML.name_unmangle(a),sxu.quoteattr(v)))
    if attrs:
        tag_open = '<%s %s>' % (element.xml_name(), ' '.join(attrs))
    else:
        tag_open = '<%s>' % element.xml_name()

    processing_lines = ''
    processing_after = False  #write processing instruction after the element
    if callable(processing):
        try:
            ret = processing(element)
            if ret:
                for target,data in ret:
                    processing_lines = '<?%s %s?>' % (target, data)
                    if 'id=' in data:
                        processing_after = True
        except:
            pass

    content = ''

    if isinstance(element, _brailleMusicML._ElementText):
        content = sxu.escape(unicode(element.text), entities)
    elif isinstance(element, _brailleMusicML._ElementValue):
        content = sxu.escape(unicode(element.value), entities)
#    elif isinstance(element, _brailleMusicML._ElementProxy):
#        pass
#    elif element.is_container():
    elif hasattr(element, '_is_container') and element._is_container:
        content = []
        for e in element:
            content.append(_writeElement(e, processing))
        content = ''.join(content)

    if content:
        tag_close = '</%s>' % element.xml_name()
        if processing_after:
            return tag_open + content + tag_close + processing_lines
        return tag_open + processing_lines + content + tag_close
    else:
        tag_open_close = tag_open[:-1] + '/>'
        return tag_open_close + processing_lines


##def _writeGraphics(element):
##    """ write Graphics object """
##    tags = []
##    for a in element.graphics._attrs:
##        attrs = ''
##        param = getattr(element.graphics, a)
##        if hasattr(param, '_attrs'):
##            attrs = []
##            for sub_a in param._attrs:
##                sub_param = getattr(param, sub_a)
##                if sub_param != None:
##                    attrs.append('%s=%s' % (sub_a, sxu.quoteattr(unicode(sub_param).strip('()'))))
##            attrs = ' '.join(attrs)
##        else:
##            if param != None:
##                attrs = 'value=%s' % sxu.quoteattr(unicode(param).strip('()'))
##        if attrs:
##            tags.append('<%s %s/>' % (a, attrs))
##    if tags:
##        tag_open = '<%s>' % element.graphics.xml_name()
##        tag_close = '</%s>' % element.graphics.xml_name()
##        return tag_open + ''.join(tags) + tag_close
##    return ''


def write(filename_or_stream, root, doctype=True, processing=None):
    """ write a BMML document to a file or a stream
        filename_or_stream: a file name or an open stream
        root: root element
        doctype: if True write also the doctype info
        processing: function to get other data to be written as processing instruction
            post_processing(element) returns a tuple (target, list of data)
    """
    if hasattr(filename_or_stream, 'write'):
        fstream = filename_or_stream
    elif isinstance(filename_or_stream, basestring):
        fstream = codecs.open(filename_or_stream, encoding='utf-8', mode='w')
    else:
        raise ValueError, 'parameter %s is not a stream or filename' % str(filename_or_stream)
    if doctype:
        fstream.write('<?xml version=\"1.0\" encoding=\"UTF-8\"?>')
        fstream.write('<!DOCTYPE score>')
        #fstream.write('<!DOCTYPE score-partwise PUBLIC \"-//Recordare//DTD MusicXML 2.0 Partwise//EN\" \"http://www.musicxml.org/dtds/partwise.dtd\">')
    fstream.write(_writeElement(root, processing=processing))
    fstream.flush()